package com.gws.juc;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * 线程池的使用
 * @author gws
 *
 * ThreadPoolExecutor 中的7大参数（重点）
 * 1. int corePoolSize 线程池中常驻的线程数
 * 2. int maximumPoolSize 线程次中能容纳同时执行的最大线程数，必须大于1
 * 3. long keepAliveTime, 多余的空闲线程存活时间，当线程池中的数量超过corePoolSize时，当空闲时间到达keepAliveTime，多余的线程会被销毁
 * 4. TimeUnit unit, keepAliveTime的单位
 * 5. BlockingQueue<Runnable> workQueue, 任务队列，被提交但尚未执行的任务
 * 6. ThreadFactory threadFactory, 表示线程池中工作线程的线程工厂，用于创建线程，（一般默认即可）
 * 7. RejectedExecutionHandler handler 拒绝策略，表示当队列满了，并且工作线程大于等于最大线程数maximumPoolSize时如何来拒绝请求执行的runnable的策略
 *
 */
public class MyThreadPoolDemo {
	public static void main(String[] args) {
		
		System.out.println(Runtime.getRuntime().availableProcessors()); //获取cpu核数
		// maximumPoolSize 一般设置为cpu核数+1
		//ExecutorService threadPool = Executors.newFixedThreadPool(3);//固定数的线程池
		//ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程 1个线程
		//ExecutorService threadPool = Executors.newCachedThreadPool();//可以自动扩充的线程池 n个线程
		ExecutorService threadPool = new ThreadPoolExecutor(2, 3, 2L, TimeUnit.SECONDS,
				new LinkedBlockingQueue<>(3),
				new ThreadPoolExecutor.AbortPolicy());
		
		
		try {
			for (int i = 1; i <= 10; i++) {
				final int n = i;
				try {
					TimeUnit.MILLISECONDS.sleep(200);
				} catch (Exception e) {
					e.printStackTrace();
				}
				threadPool.execute(() -> {
					System.out.println(Thread.currentThread().getName()+"获取："+n);
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			threadPool.shutdown();
		}
		
		
	}
	

}
